package com.doraz.orb.methods.media;

import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.doraz.orb.Constants;
import com.doraz.orb.methods.OrbMethod;
import com.doraz.orb.structs.OrbObject;
import com.doraz.orb.utils.XMLUtils;

public class Search extends OrbMethod {
	
	/**
	 * Represents a search
	 * 
	 * @param q			the query, or null to strictly user filter
	 * @param filter	the filter to use (or null for none)
	 */
	public Search(String q, String filter) {
		super("media.search", "xml/media.search", Constants.RETURN_XML);
		if(q == null){
			//Use filter instead
			addParam("filter", filter);
		}
		else {
			addParam("q", filter);
			if(filter != null) {
				addParam("filter", "q");
			}
		}
		addParam("fields", Constants.FIELDS);
		this.TAG = "Search";
	}
		
	@Override
	public OrbObject parseResponse(InputStream in) {
		Document doc = XMLUtils.getDocument(in);
		NodeList resultList = doc.getElementsByTagName("searchResult");
		if(resultList.getLength() == 0) {
			Log.w(TAG, "ERROR: No Result Elements Found");
			return null;
		}
		
		Element resultEl = (Element) resultList.item(0);
		return XMLUtils.parseResult(resultEl);
	}
}
